package com.nbsaas.boot.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtils {

    public static String getIpAddress() {
        // 获取当前请求的ServletRequestAttributes
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes != null) {
            // 从ServletRequestAttributes中获取HttpServletRequest
            HttpServletRequest request = attributes.getRequest();

            String ip = request.getHeader("X-Real-IP");
            if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
            ip = request.getHeader("X-Forwarded-For");
            if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                // 多次反向代理后会有多个IP值，第一个为真实IP。
                int index = ip.indexOf(',');
                if (index != -1) {
                    return ip.substring(0, index);
                } else {
                    return ip;
                }
            } else {
                return request.getRemoteAddr();
            }
        }
        return null; // 如果无法获取ServletRequestAttributes或HttpServletRequest，返回null或适当的默认值
    }
    public static Long getIp() {
        return ipToLong(getIpAddress());
    }
    public static String longToIp(Long ipAddress) {
        if (ipAddress == null) {
            return "";
        }
        // 使用InetAddress工具类将长整型转换为IP地址字符串
        try {
            return InetAddress.getByName(String.valueOf((ipAddress >> 24) & 0xFF) + "." +
                    ((ipAddress >> 16) & 0xFF) + "." +
                    ((ipAddress >> 8) & 0xFF) + "." +
                    (ipAddress & 0xFF)).getHostAddress();
        } catch (UnknownHostException e) {
            return "";
        }
    }

    public static Long ipToLong(String ipAddress) {
        if (!StringUtils.hasText(ipAddress)) {
            return null;
        }
        String[] ipAddressInArray = ipAddress.split("\\.");

        long result = 0;
        for (int i = 0; i < ipAddressInArray.length; i++) {
            int octet = Integer.parseInt(ipAddressInArray[i]);
            result |= (octet & 0xFF) << ((3 - i) * 8);
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(longToIp(-1062731667L));
    }
}
